#if DEBUG_VERSION
if (!dafos) {
  throw new Error("Dafos namespace not found!");
}
#endif

#if NEWSTAB

dafos.onNewsTabActivated = function() {
  if (dafos.newstab == null) {
    dafos.newstab = new dafos.NewsTab(document.getElementById("newstab"), dafos.ui);
  }
  TRACK("tab/news");
  RESIZE();
};

/**
 * Constructor
 */
dafos.NewsTab = function(parent, ui) {
  LOG("[NewsTab]");
  this.entries_ = [];
  this.appengine = new dafos.AppEngine();
  var callbacks = {
  };
  this.gadgetui = ui;
  this.ui = new dafos.NewsTabUI(parent, callbacks);

  var feeds = [];
  feeds.push({
    name : "myspace",
    url : "http://feeds.feedburner.com/myspace/rOsQ?format=xml",
    type : "dom"
  });
  feeds.push({
    name : "opensocial",
    url : "http://feeds.feedburner.com/OpensocialApiBlog?format=xml",
    type : "dom"
  });
  feeds.push({
    name : "orkut",
    url : "http://feeds.feedburner.com/OrkutDeveloperBlog?format=xml",
    type : "dom"
  });
  feeds.push({
    name : "hi5",
    url : "http://www.hi5networks.com/developer/atom.xml",
    type : "dom"
  });
  feeds.push({
    name : "igoogle",
    url : "http://feeds.feedburner.com/IgoogleDeveloperBlog?format=xml",
    type : "dom"
  });
  feeds.push({
    name : "ning",
    url : "http://feeds.feedburner.com/FeaturedBlogPosts-NingDeveloperNetwork?format=xml",
    type : "dom"
  }); 
  
  this.init_callback_ = new ark.AggregateCallback(
      dafos.bind(this.onLoaded, this), feeds.length);
  
  for (var i = 0, feed; feed = feeds[i]; i++) {
    this.gadgetui.showLoading(feed.name);
    if (feed.type == "feed") {
      this.getFeedData(feed.url, dafos.bind(this.onFeedData, this, feed.name));      
    } else {
      this.getDomData(feed.url, dafos.bind(this.onDomData, this, feed.name));      
    }
  }
};

dafos.NewsTab.prototype.getFeedData = function(url, callback) {
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
    gadgets.io.ContentType.FEED;
  params[gadgets.io.RequestParameters.GET_SUMMARIES] = true;
  gadgets.io.makeRequest(url, callback, params);
};

dafos.NewsTab.prototype.getDomData = function(url, callback) {
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
    gadgets.io.ContentType.DOM;
  gadgets.io.makeRequest(url, callback, params);
};

dafos.NewsTab.prototype.onFeedData = function(tag, response) {
  this.gadgetui.hideLoading(tag);
  LOG("[onFeedData]", tag, response);
  
  if (!response.data) {
    //TODO: report this back to appengine
    LOG("ERROR: failed to parse dom data");
    this.init_callback_.callback();  
    return;
  }
  
  //Weird hack for friendster's feed parsing code
  var items = response.data.Entry || response.data.items || [];
  for (var i = 0, entry; entry = items[i]; i++) {
    this.entries_.push({
      feed_link: response.data.Link || response.data.link,
      feed_title: response.data.Title || response.data.title,
      entry_title: entry.Title || entry.title,
      entry_time: entry.Date || entry.date,
      entry_link: entry.Link || entry.link,
      entry_summary: entry.Summary || entry.summary || entry.description
    });
  }
  this.init_callback_.callback();  
};

dafos.NewsTab.prototype.onDomData = function(tag, response) {
  this.gadgetui.hideLoading(tag);
  LOG("[onDomData]", tag, response);

  if (!response.data) {
    //TODO: report this back to appengine
    LOG("ERROR: failed to parse dom data");
    this.init_callback_.callback();  
    return;
  }
  
  var entries = response.data.getElementsByTagName("entry");
  var feed_node = response.data.getElementsByTagName("feed")[0];
  var feed_link = "";
  var feed_title = ""
  for (var i = 0, child; child = feed_node.childNodes[i]; i++) {
    switch (child.tagName) {
      case "title":
        feed_title = child.textContent || child.text;
        break;
      case "link":
        if (child.attributes.getNamedItem("rel").nodeValue == "alternate") {
          feed_link = child.attributes.getNamedItem("href").nodeValue;
        }
        break;   
    }
  }
  for (var i = 0, entry; entry = entries[i]; i++) {
    var entry_data = {};
    entry_data.feed_title = feed_title;
    entry_data.feed_link = feed_link;
    for (var j = 0, child; child = entry.childNodes[j]; j++) {
      switch (child.tagName) {
        case "title":
          entry_data.entry_title = child.textContent || child.text;
          break;
        case "updated":
          var text = child.textContent || child.text;
          var dateparts = text.substr(0, 10).split("-");
          var month = dafos.monthToString(Number(dateparts[1]));
          var day = dateparts[2];
          var year = dateparts[0];
          var date = month + " " + day + " " + year;
          var time = text.substr(11, 8);
          if (text.length == 25) {
            var tz = " UTC" + text.substr(19, 6).split(":").join("");
          } else {
            var tz = "";
          }
          entry_data.entry_time = Date.parse(date + " " + time + tz);
          break;
        case "content":
        case "summary":
          entry_data.entry_summary = child.textContent || child.text;
          break;
        case "link":
          if (child.attributes.getNamedItem("rel").nodeValue == "alternate") {
            entry_data.entry_link = 
                child.attributes.getNamedItem("href").nodeValue;
          }
          break;
      }
    }
    this.entries_.push(entry_data);
  }
  this.init_callback_.callback();  
};

dafos.NewsTab.prototype.onLoaded = function() {
  LOG("[onLoaded]");

  this.entries_.sort(this.entrySorter);
  this.ui.show();
  for (var i = 0, entry; entry = this.entries_[i]; i++) {
    if (i >= 15) {
      break;
    }
    this.ui.renderEntry(entry);
  }
};

dafos.NewsTab.prototype.entrySorter = function(a, b) {
  return b.entry_time - a.entry_time;
};



/**
 * Constructor
 */
dafos.NewsTabUI = function(parent, callbacks) {
  LOG("[NewsTabUI]");
  this.dom_parent_ = parent;
  this.render(callbacks);
};

dafos.NewsTabUI.prototype.render = function(callbacks) {
  e34.$("newstab").removeClass("hidden");
  
  this.entry_counter = 0;
  this.toc_template = e34.$("newstab-toc-template");
  this.toc_parent = e34.$(this.toc_template.getParentElement());
  this.toc_template.removeFromParent();
  
  this.entry_template = e34.$("newstab-entries-item-template");
  this.entry_parent = e34.$(this.entry_template.getParentElement());
  this.entry_template.removeFromParent();
};

dafos.NewsTabUI.prototype.show = function() {
  e34.$("newstab-content").removeClass("hidden");
};

dafos.NewsTabUI.prototype.renderEntry = function(entry) {
  this.entry_counter++;
  var toc_row = e34.renderTemplate(this.toc_template, { 
    entry_id: this.entry_counter,
    class_name: (this.entry_counter % 2 == 0) ? "even" : "odd",
    link: entry.entry_link,
    title: entry.entry_title,
    feed_title: entry.feed_title,
    time: dafos.timeToPrettyString(entry.entry_time)
  });
  this.toc_parent.appendChildren(toc_row);
  
  var entry_row = e34.renderTemplate(this.entry_template, { 
    entry_id: this.entry_counter,
    link: entry.entry_link,
    title: entry.entry_title,
    feed_title: entry.feed_title,
    feed_link: entry.feed_link,
    time: dafos.timeToPrettyString(entry.entry_time),
    summary: entry.entry_summary
  });
  this.entry_parent.appendChildren(entry_row);
  
  var anchor = toc_row.$T("a")[0];
  anchor.addOnClickHandler(function (e) {
    e.preventDefault();
    entry_row.scrollIntoView();
  });
  
  gadgets.window.adjustHeight();
};


#endif
